const E = window.wangEditor
const { createEditor, createToolbar } = E
const { PanelMenu, Panel } = E;
window.formualKey = 1;
window.editKey=''
window.formualKeyHtml = ''
window.formualMap = {}
function createPanelConf(wangEditor, formulaEditor) {
  /**
   * 插入公式
   */
  function insertFomule() {
    if(window.editKey) $('#formulaKey'+editKey).remove();
    const formula = formulaEditor.$textSvgElem.html()
    const text = formulaEditor.latex.text()
    const lat = formulaEditor.$textSvgElem.text()
    if(!text) return
    //alert(1)
    // 注意插入wangEditor时左右两边的空格不能去掉，不然会导致无法获取焦点 <span key="'+formualKey+'" onclick="editFormual('+formualKey+')"">编辑</span><i onclick="deleteFormual('+formualKey+')"">删除</i>
    const html = '<p class="m-lint">&nbsp;</p><p class="formula-content" onmouseenter="mouseoverFormual('+window.formualKey+')" onmouseleave="mouseoutFormual('+window.formualKey+')" data-formult="'+text+'" id="formulaKey'+window.formualKey+'">' + formula + '</p><p class="m-lint">&nbsp;</p>'
    wangEditor.cmd.do('insertHTML', html)
    formulaEditor.destoryDom()
    
    window.formualMap[String(lat)] = text
    window.formualKey++
    return true
  }
  // 编辑
  window.editFormual = function(key) {
    setTimeout(()=>{
      window.editKey = key
      $('#formulaEditorButton').click()
      const text = $('#formulaKey'+key).attr('data-formult')
      formula.append(text);
    },30)
  }
  // 移入
  window.mouseoverFormual = function(key){
      $('#formulaKey'+key).append('<span class="edit-formual" onclick="editFormual('+key+')"">编辑</span><i class="delete-formual" onclick="deleteFormual('+key+')"">删除</i>')
  }
  // 移出
  window.mouseoutFormual = function(key){
      $(".edit-formual").remove()
      $(".delete-formual").remove()
  }
  // 删除
  window.deleteFormual = function(key) {
    setTimeout(()=>{
      $('#formulaKey'+key).remove();
    },30)
  }
  // tabs配置
  const tabsConf = [
    {
      // tab 的标题
      title: "数学公式",
      // 模板
      tpl: `<div>
              <div id="edit-content"></div>
              <div class="w-e-button-container">
                <button type="button" id="btn-ok" class="right">确定</button>
              </div>
            </div>`,
      // 事件绑定
      events: [
        // 插入视频
        {
          selector: '#btn-ok',
          type: 'click',
          fn: insertFomule,
          bindEnter: true,
        },
      ],
    }, // tab end
  ]
  return {
    width: 330,
    height: 0,
    // panel 中可包含多个 tab
    tabs: tabsConf, // tabs end
  }
}

class MyMenu  extends PanelMenu {
    constructor(editor) {
      // data-title属性表示当鼠标悬停在该按钮上时提示该按钮的功能简述
      const $elem = E.$(
        `<div class="w-e-menu" id="formulaEditorButton" data-title="数学公式">
          <span>公式</span>
        </div>`
      );
      super($elem, editor);
    }
    /**
     * 菜单点击事件
     */
    clickHandler() {
      window.formula = new formulaEditor();
      const conf = createPanelConf(this.editor, formula);
      const panel = new Panel(this, conf);
      panel.create();
      formula.create("#edit-content");
    }
}
// 注册菜单
E.registerMenu("math-formula", MyMenu);
window.editor = new E("#editor-container");
editor.config.menus = [
  'head',
    'bold',
    'fontSize',
    'fontName',
    'italic',
    // 'underline',
    'strikeThrough',
    'indent',
    // 'lineHeight',
    'foreColor',
    // 'backColor',
    // 'link',
    // 'list',
    // 'todo',
    'justify',
    // 'quote',
    // 'emoticon',
    // 'image',
    // 'video',
    // 'table',
    // 'code',
    // 'splitLine',
    'undo',
    'redo',
]
editor.create();

const vscode = acquireVsCodeApi();

window.addEventListener('message', event => {
    if ("predictions" in event.data) {
        predictions= event.data.predictions;
        let markHtml = marked.parse(predictions);
        setCode(markHtml);
    } else if ("colorTheme" in event.data){
        let colorTheme=event.data.colorTheme;
        var page = colorTheme.indexOf("Dark")!==-1? "white":'black'; // white, black
        document.body.className = page;
    }
});

function generate(){
    if(!document.getElementById('c-button').className) {return ;}
    vscode.postMessage({"config":document.getElementById("dict").value,"pseudoCode":getEditorText()});
}
// 获取富文本中的文本内容
function getEditorText(){
  let text = editor.$textElem.text().replaceAll('编辑删除','')
  for(let key in window.formualMap){
      text = text.replaceAll(key,window.formualMap[key])
  }
  text = text.replaceAll('&nbsp',' ')
  console.log(text)
  return text
}
editor.config.onchange = function (newHtml) {
  if(newHtml && document.getElementById('pseudoCode').value){
      document.getElementById('c-button').className = 'active';
  }else{
      document.getElementById('c-button').className = '';
  }
};
document.addEventListener('contextmenu', function(e) {
  e.preventDefault();
});